﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace ApiScanner.Core
{
    internal sealed class ExchangeDllDependencyScannerModule : IFileSystemScannerModule
    {
        private readonly IList<string> _DllNames = new List<string> { "Mapi32.DLL", "CDOEX.DLL", "Cdoexm.DLL", "CDO.DLL", "EXOLEDB.DLL" };
        public IEnumerable<string> FilePatterns
        {
            get
            {
                yield return "*.exe";
                yield return "*.dll";
            }
        }

        public Artifact Execute(string file, FileSystemScannerModuleConfigurationElement configuration)
        {
            var id = Guid.NewGuid().ToString();
            var tempFile = Path.Combine(Path.GetTempPath(), string.Format("{0}.csv", id));

            var process = Process.Start("depends.exe", string.Format("/c /oc:\"{0}\" \"{1}\"", tempFile, file));
            process.WaitForExit();

            var log = File.ReadAllText(tempFile);
            File.Delete(tempFile);

            var dependencies = (from filename in _DllNames
                                where log.IndexOf(filename, StringComparison.OrdinalIgnoreCase) != -1
                                select filename);
            if (dependencies.Any())
            {
                return new FileSystemArtifact(file, dependencies);
            }
            return null;
        }
    }
}